package com.weiaibenpao.demo.chislim.ui.activity.running;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.PolylineOptions;
import com.orhanobut.logger.Logger;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.bean.SportOverInfoBean;
import com.weiaibenpao.demo.chislim.db.entities.RunningRecord;
import com.weiaibenpao.demo.chislim.service.RunningService;
import com.weiaibenpao.demo.chislim.tts.util.SpeechUtil;
import com.weiaibenpao.demo.chislim.ui.fragment.InterestRunFragment;
import com.weiaibenpao.demo.chislim.utils.Constant;
import com.weiaibenpao.demo.chislim.utils.RunningUtils;
import com.weiaibenpao.demo.chislim.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import io.objectbox.query.Query;

public class InterestInRunActivity extends BaseRunningActivity {

    protected float setDistance;
    protected float currentRunDis;
    private LatLng mLatLng;
    private List<LatLng> mLatLngList = new ArrayList<>();
    protected double longitude;
    protected double latitude;
    protected boolean  isPolyLineOver=false;
    protected int totalNum;
    protected float beforeDis;//每次更新数据之前的距离
    protected List<PolylineOptions> optionsList;
//    protected StringBuilder mLocusPhoto = new StringBuilder();       //轨迹
//    protected StringBuilder mFrequencyPhoto = new StringBuilder();   //步频图
//    protected StringBuilder mStridePhoto = new StringBuilder();      //步幅图
//    protected StringBuilder mPaceForm = new StringBuilder();         //配速列表
//    protected StringBuilder mAltitudePhoto = new StringBuilder();    //海拔图

    protected String mCalorie;
    protected String totalStep;
//    protected StringBuilder mInterestPoint=new StringBuilder();//趣味跑数据格式
    public static void startSelf(Context context, float setDistance, double latitude, double longitude) {
        Intent intent = new Intent(context, InterestInRunActivity.class);
        intent.putExtra(Constant.RUN_DISTANCE, setDistance);
        intent.putExtra(Constant.LATITUDE,latitude);
        intent.putExtra(Constant.LONGITUDE,longitude);
        context.startActivity(intent);
    }
    protected boolean isOutOrIn() {
        return true;
    }
    @Override
    public void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        setDistance = getIntent().getFloatExtra(Constant.RUN_DISTANCE, 0);
        latitude = getIntent().getDoubleExtra(Constant.LATITUDE, 39.906901);
        longitude = getIntent().getDoubleExtra(Constant.LONGITUDE, 116.397972);
        Logger.e("setDistance   "+setDistance);
        totalNum = InterestRunFragment.totalNum;//总的点数
        initDrawLine();
//        if (options == null) {
//            options = new PolylineOptions();
//            options.width(15).color(getResources().getColor(R.color.color_run));
//        }
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude),15f));


    }

    private void initDrawLine() {
//        for(int i= 0 ;i<InterestRunFragment.twoPointLineList.size();i++){
//            List<LatLng> latLngs = InterestRunFragment.twoPointLineList.get(i).getLatLngs();
//            PolylineOptions options = new PolylineOptions();
//            options.width(15).color(getResources().getColor(R.color.color_un_run)).zIndex(200).visible(true);
//            options.addAll(latLngs);
//            aMap.addPolyline(options);
//            if (i==InterestRunFragment.twoPointLineList.size()-1){
//                mInterestPoint.append(latLngs.get(0)).append(",").append(latLngs.get(1)).append(";");
//            }else {
//                mInterestPoint.append(latLngs.get(0)).append(",").append(latLngs.get(1)).append(":");
//            }
//        }
        for(int i=0;i<InterestRunFragment.optionsList.size();i++){
            aMap.addPolyline(InterestRunFragment.optionsList.get(i));
        }
    }

//

    @Override
    protected void putExtraToServiceIntent(Intent serviceIntent) {
        super.putExtraToServiceIntent(serviceIntent);
        serviceIntent.putExtra(RunningService.NEED_SAVE_RECORD, false);
        serviceIntent.putExtra(RunningService.NEED_EXTRA_DATA, false);
        serviceIntent.putExtra(RunningService.NEED_SAVE_STATE, false);
        serviceIntent.putExtra(RunningService.IS_INDOOR_RUNNING,true);

    }
    /**
     *  Created by ZJL
     *  Algorithm supported by ZJL
     *  优雅版：自动处理断笔绘制 无重复绘制
     */
    private int lastProgress = 0;
    private void doDrawLine(float currentRunDis){ //注意传入的距离不能大于setDistance否则数组越界
        int  currentProgress = (int) (currentRunDis/setDistance*InterestRunFragment.twoPointLineList.size());
        for(int i= lastProgress ;i<currentProgress;i++){
            PolylineOptions options = new PolylineOptions();
            options.width(15).color(getResources().getColor(R.color.color_run)).zIndex(200).visible(true);
            options.addAll(InterestRunFragment.twoPointLineList.get(i).getLatLngs());
            aMap.addPolyline(options);
        }
        lastProgress = currentProgress;
        if(currentProgress == InterestRunFragment.twoPointLineList.size()){
            isPolyLineOver = true;
            SpeechUtil.getInstance().speak("恭喜，趣味图形已绘制完成");
        }
    }


    /**
     *  Created by ZJL
     *  Algorithm supported by ZJL
     *  高效版：合纵连横  属于同一笔上的线段的坐标拼起来一次性给PolylineOptions,减少aMap.addPolyLine执行次数，但是需要判断断笔  不过依然无重复绘制
     *  ----适用于每次新增的progress数量很大的情况 即每次currentProgress-lastProgress差值很大的情况
     *  注意：这里高效是指可以显著少的执行aMap.addPolyLine  实际性能未必，需要测试，因为PolylineOptions里面不管传入的是两点还是多点最终绘制本质
     *  还是每两点绘制一下，然后连起来--即绘制过程本质还是类似doDrawLine()
     */
    private  void  doDrawLine2(float currentRunDis){
        int  currentProgress = (int) (currentRunDis/setDistance*InterestRunFragment.twoPointLineList.size());
        ArrayList<List<LatLng>> allPolyLineList = new ArrayList<>();
        ArrayList<LatLng> polyLineList = new ArrayList<>();
        for(int i= lastProgress ;i<currentProgress;i++){
            if(lastProgress >0 && InterestRunFragment.twoPointLineList.get(i).isStartLine()){
//                allPolyLineList.add((List<LatLng>) (polyLineList.clone()));
                allPolyLineList.add(polyLineList);
                polyLineList = new ArrayList<>();
            }else if(i == (currentProgress-1)){
                allPolyLineList.add(polyLineList);
            }
            polyLineList.addAll(InterestRunFragment.twoPointLineList.get(i).getLatLngs());
        }
        for (int j=0;j<allPolyLineList.size();j++){
            PolylineOptions options = new PolylineOptions();
            options.width(15).color(getResources().getColor(R.color.color_run)).zIndex(200).visible(true);
            options.addAll(allPolyLineList.get(j));
            aMap.addPolyline(options);
        }
        lastProgress = currentProgress;
        if(currentProgress == InterestRunFragment.twoPointLineList.size()){
            isPolyLineOver = true;
            SpeechUtil.getInstance().speak("恭喜，趣味图形已绘制完成");
        }
    }

    private void drawPoint(float currentRunDis) {
//        int currentNum = (int) ( totalNum* (currentRunDis / setDistance));//计算当前的总共点数
//        if (totalNum>=currentNum) {
//            for (int i = 0; i < optionsList.size(); i++) {
//                PolylineOptions options1 = optionsList.get(0);
//                int size = options1.getPoints().size();
//                if (currentNum < size) {
//                    for (int j = runPoint; j < currentNum; j++) {//绘制的时候需要从上次节点开始取数
//                        options.add(options1.getPoints().get(j));
//
//                    }
//                    aMap.addPolyline(options);
//
//                    Logger.e("正在绘制<size：" + runPoint+"  size=="+size);
//                    runPoint = currentNum;
//                } else if (currentNum >= size) {
//                    runTotalNum+=size;
//                    currentNum -= size;
//                    if (size >= runPoint) {
//                        for (int j = runPoint; j < size; j++) {//绘制的时候需要从上次节点开始取数
//                            options.add(options1.getPoints().get(j));
//                        }
//                        aMap.addPolyline(options);
//
//                        Logger.e("正在绘制>size：" + runPoint);
//                        runPoint = 0;
//                        optionsList.remove(0);
//                        options.getPoints().clear();
//                        continue;
//                    }
//
//                }
//            }
//    }
    }

    @Override
    protected void updateMap() {
        super.updateMap();
        //每当本次的距离大于更新之前的距离需要去绘制
//       if (this.currentRunDis>beforeDis&&!isPolyLineOver){
//           drawLine(this.currentRunDis);
//           beforeDis=this.currentRunDis;
//       }
        if(!isPolyLineOver ){
            if(currentRunDis> setDistance) {//超出目标距离的部分不绘制
                doDrawLine(setDistance);
            }else {
                doDrawLine(currentRunDis);
            }
        }
    }


    @Override
    protected boolean shouldShowCurrentLocation() {
        return false;
    }

    @Override
    public void onDataUpdated(Bundle data) {
        super.onDataUpdated(data);
        this.currentRunDis = data.getFloat(RunningService.DISTANCE)/1000;
//        if (!isPolyLineOver&&this.currentRunDis >= setDistance) {
//            SpeechUtil.getInstance().speak("恭喜，趣味图形已绘制完成");
//            isPolyLineOver=true;
//            drawLines();
//        }
        mCalorie=data.getString(RunningService.CALORIE);
        totalStep=data.getString(RunningService.STEP);

        currentRunDis = data.getFloat(RunningService.DISTANCE)/1000;
//        if (!isPolyLineOver&&this.currentRunDis >= setDistance) {
//            isPolyLineOver =true;
//            SpeechUtil.getInstance().speak("恭喜，趣味图形已绘制完成");
//            doDrawLine(setDistance);
//        }
        Logger.e("currentRunDis=="+this.currentRunDis);
        mLatLng = data.getParcelable(RunningService.LAT_LNG);
        mLatLngList.add(mLatLng);
        updateMap();
    }

    @Override
    protected void uploadRunningData() {
        super.uploadRunningData();
        Query<RunningRecord> query = mRunningRecordBox.query().build();
        List<RunningRecord> records = query.find();
        assembleDataFromDatabase(records);
        if(isDestroyed()){
            return;
        }
        if(!Utils.isNetWorkConnected()){
            Toast.makeText(this, getString(R.string.network_not_connected), Toast.LENGTH_SHORT).show();
            return;
        }
        doUpLoad();

    }
    @Override
    public void onRunningTime(int runningTime) {
        super.onRunningTime(runningTime);
        runningDataView.setTime(RunningUtils.getHmsTime(runningTime));
    }
    protected void doUpLoad() {
        mPresenter.postRunData(userId,4,45,String.valueOf(marathonType),"","",0,mCalorie,
                setDistance+"","",String.valueOf(mFrequencyPhoto)
                ,"",String.valueOf(mPaceForm),
                String.valueOf(InterestRunFragment.mInterestPoint) ,"",
                totalNum,mTotalTime,totalStep,currentRunDis);
    }

    private void assembleDataFromDatabase(List<RunningRecord> list) {
//        protected StringBuilder mStridePhoto = new StringBuilder();      //步幅图
//        protected StringBuilder mLocusPhoto = new StringBuilder();       //轨迹
        List<RunningRecord> records  = list;

        for(int i=0;i<records.size();i++){
            RunningRecord record = records.get(i);
            String timeStr = String.valueOf(record.getTime());
            mFrequencyPhoto.append(timeStr).append(":").append(record.getFrequency()).append(",");
            //配速格式为 整公里数：配速：时间，
            if(!TextUtils.isEmpty(record.getKmPace())){
                mPaceForm.append(record.getKmValue()).append(":").append(record.getKmPace()).append(":").append(timeStr).append(",");
            }
        }
    }
    @Override
    public void onUploadDataSuccess(SportOverInfoBean sportInfoBean) {
        super.onUploadDataSuccess(sportInfoBean);
        ShareActivity.startSelf(this,sportInfoBean,"趣味·室内","");
        doFinish();
    }
}
